<!-- 登录页 -->
<template>
	<view>
		<form @submit="handleSubmit">
			<view class="get-user">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="avatarUrl" style="width: 56px !important;"></image>
					<view style="margin-top: 40rpx;">点击获取用户头像</view>
				</button>
				<view class="nickname">
					<view style="width: 120rpx;">昵称</view>
					<input type="nickname" name="nickname" placeholder="点击选择昵称" />
				</view>
				<view class="nickname2 flex-between">
					<view class="flex-align-center">
						<view style="width: 120rpx;">电话</view>
						<input type="number" maxlength="11" v-model="mobile" class="font-overflow"
							placeholder="点击获取电话" />
					</view>
					<!-- 将获取到的手机号直接复制给input的mobile -->
					<button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
						class="btn_phone">获取手机号</button>
				</view>
				<view class="submit-userinfo">
					<!-- 获取头像登录 -->
					<view style="text-align: center;"><button :disabled="loading" type="primary" form-type="submit"
							size="mini" class="logins">登录</button></view>
                    
				<!-- 	<view style="text-align: center;margin-top: 30rpx;">
						<button type="default" :disabled="loading" @click="getUserProfile" hover-class="sunui-hover" size="mini"
							class="falls">默认登录</button>
					</view> -->
				</view>
			</view>
		</form>
	</view>
</template>

<script>
	import {

		mapMutations
	} from 'vuex'
	import {
		mapState
	} from 'vuex'
	import {
		mapGetters
	} from 'vuex'
	import {
		object2Url
	} from '@/utils/trans';
	import util from '@/we7/resource/js/util.js';
	export default {
		data() {
			return {
				system: {},
				nickName: '',
				avatarUrl: '/static/avatar.png',
				mobile: '',
				// 是否登录页进入
				isRenovate: 0,
				// 是否团购商品详情页进入
				isGroup: 0,
				// 是否发布页进入
				isNeed: 0,
				// 产品id
				goodsId: '',
				uids: '',
				uid: '',
				loading: false,
				storageMode:'',
				
				tap: '',
			};
		},
		onLoad(options) {
			this.isNeed = options.isNeed;
			this.isGroup = options.isGroup;
			this.goodsId = options.goods_id;
			this.uids = options.uid;
			this.isRenovate = options.isRenovate;
			if (options.tap){
				this.tap = options.tap;
			}
			this.getUploadConfig()
			this.getSiteDomainID()
		},
		onReady() {
			this.$sun.title('登录授权');
		},
		
		onHide() {
			console.log("--------1111");
			if (this.tap == 1){
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		
		onUnload() {
			console.log("--------3333");
			if (this.tap == 1){
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		
		onBackPress() {
			console.log("--------222");
			if (this.tap == 1){
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		
		methods: {
			...mapMutations('user', ['authorizationInformationFn']),
			// 获取手机号
			async getSiteDomainID() {
			     const url =this.$api.getSiteDomainName
			     const siteDomainName=url.match(/^(?:https?:\/\/)?([^\/]+)/i)[1];
			     console.log(siteDomainName)
				// uploadQualificationForm','uploadHealthCertificateForm','uploadAvatarForm','identityAuthenticationForm
				const result = await this.$http.get({
					url: this.$api.getSiteDomainName,
					data: {
						siteDomainName: siteDomainName // 站点域名(传值将https截取)
					}
				});
			
				if (result.code == 200) {
					// ‘冻结’弹出框

					if(result.data){
						uni.setStorageSync('siteId', result.data.id)
						console.log('根据站点域名查询站点result.', result);
						
						const ress = await this.$http.get({
							url: this.$api.withdrawalSettings,
							data: {
								siteId: uni.getStorageSync('siteId') // 站点域名(传值将https截取)
							}
						
						})
						
						
						uni.setStorageSync('withdrawalMethod', ress.data)
						this.sharePictures()
					}
			
				} else {
					this.$sun.toast(result.message)
				}
			
			},
			async sharePictures(){
				const res = await this.$http.get({
					url: this.$api.sitePlatformConfig,
					data: {
						siteId:uni.getStorageSync('siteId')
					}
				});
				console.log(res.data+'==============分享图片')
				// 分享标题
				wx.setStorageSync('system',res.data )
				// 分享图片
				// wx.setStorageSync('system',res.data.sharePictures)
				// 分享描述
				// wx.setStorageSync('system',res.data.shareDescribe)
			},
			onGetPhoneNumber(e) {
				console.log("-----------------",e);
				this.getKeyByCode(e.detail.code);
				// var _that = this;
				// 用户点击了接受
				// if (e.detail.errMsg == 'getPhoneNumber:ok') {
				// 	let encryptedData = e.detail.encryptedData;
				// 	let errMsg = e.detail.errMsg;
				// 	let iv = e.detail.iv;
				// 	const code = e.detail.code;
				// 	_that.cc = code;
				// 	console.log(_that.cc)
				// 	this.getKeyByCode(_that.cc);
				// } else {
				// 	/* uni.switchTab({
				// 		url: '/pages/index/index'
				// 	}); */
				// }
			},
			// 获取手机号解密接口
			async getKeyByCode(code) {
				const result = await this.$http.get({
					url: this.$api.getPhoneCode,
					data: {
						code: code,
						siteId: String(wx.getStorageSync('siteId')),
					}
				});
				if (result.code == 1) {
					console.log('data', result.data);
					this.mobile = result.result.phone_info.phoneNumber;
					uni.setStorageSync('mobile', this.mobile);
				}
			},
			async getUploadConfig() {
				const result = await this.$http.get({
					url: this.$api.getStorageConfig,
					data: {}
				});
				if (result.code == 200) {
					this.storageMode = result.data.storageMode; // storageMode:2是‘阿里云’上传，3是‘七牛云’ 上传
					console.log('this.storageMode', this.storageMode);
			
				} else {
					console.log('result.message', result.message);
				}
			},
			handleSubmit(e) {
				// 提交到接口
				const val = e.detail.value;
				this.nickname = val.nickname;
				if (!this.nickname || !this.mobile) {
					uni.showModal({
						title: '温馨提示',
						content: `请输入用户名字，以及点击获取头像和手机号`,
						showCancel: false
					});
					return;
				}
				this.getUserProfile();
			},
			// 选择头像
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail;
				this.xixixi(avatarUrl);
			},

			async xixixi(avatarUrl) {

				if (this.storageMode == 3) {
					this.loading = true
					uni.uploadFile({
						url: this.$api.qnyOssSignature, //仅为示例，非真实的接口地址
						filePath: avatarUrl,
						name: 'file',
						formData: {

						},
						success: (res) => {
							if (res.statusCode == 200) {
								console.log('uploadImage success, res is:', res)
								uni.hideLoading();
								uni.showToast({
									title: '上传成功',
									icon: 'success',
									duration: 1000
								})
								this.upLoadStatus = '上传成功'
								this.avatarUrl = JSON.parse(res.data).data.url

							}
                            this.loading = false


						},
						fail: (err) => {
							if (this.pageVisible) {
								console.log('uploadImage fail', err);
								uni.hideLoading();
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
							}
						},
					});
				} else {
					this.loading = true
					const ts = new Date().getTime();
					// const ua = navigator.userAgent;
					const us = {
						ts,
						// ua
					};
					let url = this.$api.alyOssSignature + `${object2Url(us)}`;
					const res = await this.$http.get({
						url: url,
						data: {
							us: us
						}
					});

					let markIndex = avatarUrl.lastIndexOf('.');
					let suffix = avatarUrl.substring(markIndex);
					let date = new Date().getTime();
					
					wx.uploadFile({
						url: res.data.host, //上传的路径
						filePath: avatarUrl,
						name: 'file',
						formData: {
							name: avatarUrl,
							key: date + suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
							policy: res.data.policy,
							OSSAccessKeyId: res.data.accessId,
							success_action_status: "200",
							signature: res.data.signature,
						},
						header: {
							'Access-Control-Allow-Origin': '*',
							'x-oss-callback-Authorization': 'access_token'
						},
						success: (result) => {
							console.log('chooseImage success, temp path is: ', res)

							let url = res.data.host + '/' + date + suffix;
							console.log(url)
							this.avatarUrl = url
							wx.showToast({
								title: "上传成功",
								icon: 'success',
								duration: 1000,

							})
							this.loading = false
						},
						fail: function({
							errMsg
						}) {
							console.log('upladImage fail, errMsg is: ', errMsg)
							wx.showToast({
								title: "上传失败",
								duration: 1000
							})
						},
					})

				}
			},

			// 微擎的话自带获取用户信息,不需要重新获取code(所以都写在APP - onLaunch那里)
			handleUnAuth() {
				wx.navigateBack();
			},

			getUserProfile() {
				if (this.mobile) {
					wx.login({
						provider: 'weixin',
						success: async res => {
							console.log(res)
							const openInfo = await this.$http.get({
								url: this.$api.loginAuth,
								data: {
									siteId: String(wx.getStorageSync('siteId')),
									code: res.code,
									
								}
							});
							console.log(openInfo)
				
							if (openInfo.code == 1) {
								// let key = openInfo.data.session_key;
								var openid = openInfo.result.openid; //openid 用户唯一标识
								// 设置openid（先用微信的wx.login方法 再调用后端返回获取openid接口（传code)
								wx.setStorageSync('openid', openid);
								wx.setStorageSync('code', res.code);

								setTimeout(() => {
									uni.request({
										url: this.$api.userLogin,
										method: 'GET',
										data: {
											mobile: String(this.mobile),
											/*  * 新增微信用户
											 * @param openid
											 * @param avatar 头像
											 * @param nickname 昵称
											 * @param dy_uid 抖音uid */
											// 微信用户opendid
											openid: wx.getStorageSync('openid'),
											unionid:openInfo.result.unionid,
											// 微信用户昵称
											// nickname: user.nickName,
											// 独立小程序需要
											nickname: this.nickname ? this.nickname : '默认昵称',
											// 微信用户头像
											avatar: this.avatarUrl ? this.avatarUrl :
												'/static/avatar.png',
											// 分销pid
											// pid : pid
											// pid: uni.getStorageSync('pid') ? uni.getStorageSync('pid') : null,
											// 站点id
											siteId: String(wx.getStorageSync('siteId')),
										},
										success: async res => {
											console.log(res)
											if (res.data.msg == '校验成功') {
												uni.setStorageSync('clearStoreage', true)
												// 当前状态 为true的时候不清除
												this.uid = res.data.result
												this.$sun.toast('登录成功');
												wx.setStorageSync('userId', this.uid);

												this.$sun.navRe('/pages/my/my');
												// uni.navigateBack()
 
												// 根据 uid 获取到个人信息

												const openInfo = await this.$http.get({
													url: this.$api.getPersonInfo,
													data: {
														userId: wx.getStorageSync(
															'userId'),
														siteId: wx.getStorageSync(
															'siteId')
													}
												});
												// 员工授权信息
												// console.log(openInfo)
												this.authorizationInformationFn(openInfo
													.data)
											}else{
												this.$sun.toast(res.data.message);
											}

										},
										fail: err => {
											uni.showModal({
												title: '错误',
												content: `访问公众平台接口失败, 错误: invalid appsecret, view more at http://t.cn/RAEkdVq, hints: [ req_id: WeMfdZyFe-D3JW7 ],错误详情：无效的appsecret`,
												showCancel: false
											});
										},
										complete: info => {
											// 由于wx.getUserProfile被删除了，所以获取不到res.user
											// wx.setStorageSync('userInfo', user);
										}
									});
								}, 500);
							} else {
								setTimeout(() => {
									console.log('失败', res);
								}, 2000);
							}
						}
					});
				} else {
					this.$sun.toast('请先完成获取手机号');
				}
			}
		}
	};
</script>

<style lang="scss">
	/deep/ button::after {
		border: none;
	}

	.get-user {
		padding-top: 40px;

		.submit-userinfo {
			margin: 40rpx 0;
			margin-top: 260rpx;

			button {
				display: inline-flex !important;
				align-items: center;
				justify-content: center;
				height: 70rpx;
				line-height: 1;
				vertical-align: middle;
				-webkit-appearance: none;
				-webkit-text-size-adjust: 100%;
				box-sizing: border-box;
				font-size: 32rpx;
				white-space: nowrap;
				margin: 0;
				padding: 0rpx 120rpx;
				overflow: visible;
				border-radius: 10rpx;
				font-weight: bold;
				margin: auto;
			}

			.logins,
			.falls {
				width: 370rpx;
			}

			.logins {
				background-color: #fa5e50;
			}

			.falls {
				color: #ff7267;
				margin-top: 20rpx;
				font-weight: initial;
			}
		}

		.avatar-wrapper {
			padding: 0;
			width: 240rpx;
			border-radius: 8px;
			margin-bottom: 40px;
			color: #9b9b9b;
			background: #ffffff;
		}

		.avatar {
			display: block;
			width: 56px;
			height: 56px;
			margin: 20rpx auto;
			border-radius: 20rpx;
		}

		.nickname {
			display: flex;
			align-content: center;
			border: 1rpx solid #eee;
			padding: 32rpx;
		}

		.nickname2 {
			display: flex;
			align-content: center;
			border: 1rpx solid #eee;
			padding: 20rpx 32rpx;

			.btn_phone {
				width: 220rpx;
				text-align: right;
				color: #666666;
				background-color: #fff;
				font-size: 28rpx;
				padding: 0rpx;
			}
		}
	}
</style>